<template>
  <div class="container">
    <input style="width: 100%" v-model="text" />
    <p class="result">{{ text }}</p>
  </div>
</template>

<script setup>

// https://cn.vuejs.org/api/reactivity-advanced.html#customref
// 官网就是这么写的

import { customRef, ref } from "vue";

const debounceRef = (value, delay = 1000) => {
  let timer;
  return customRef((track, trigger) => {
    return {
      get() {
        // 依赖收集track
        track();
        return value;
      },
      set(val) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          // 派发更新trigger
          trigger();
          value = val;
        }, delay);
      },
    };
  });
};

const text = debounceRef("");
</script>

<style lang="scss" scoped></style>
